/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hisense.settings;

import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import static android.provider.Settings.System.SOUND_EFFECTS_ENABLED;

import com.android.settings.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.provider.Settings;
import android.preference.PreferenceScreen;

import java.util.List;
import android.util.Log;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import android.content.DialogInterface;

import com.hisense.settings.util.TvIntents;
import com.hisense.settings.util.Wrapper;
/*import com.marvell.willowtv.framework.features.ParentalControl;
import com.marvell.willowtv.framework.features.TvFramework;
import com.marvell.willowtv.framework.model.atsc.USDTVPCData;*/

import android.content.Intent;


import android.content.ServiceConnection;
import android.content.ComponentName;
import android.os.IBinder;
import android.os.RemoteException;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Service;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.view.View;
import android.view.ViewGroup;

/**
 * Handles settings menu for channel settings.
 * 
 * @author huangjiufa
 */
public class ParentalLockSettings extends PreferenceActivity implements
		Preference.OnPreferenceChangeListener {

	private static final String TAG = "ParentalLockSettings";

	private static final String KEY_CHANNEL_LOCK = "channel_lock";
	private static final String KEY_PROGRAM_RATING = "program_lock";
	private static final String KEY_INPUT_LOCK = "input_lock";
	private static final String KEY_INPUT_LOCK_NEW = "input_lock_new";
	private static final String KEY_CLEAR_ALL = "parental_lock_clear_all";
	private static final String KEY_LOCK_TOGGLE = "parental_lock_toggle";

	private static final int DIALOG_CHANNEL_LOCK_LIST = 10;
	private static final int DIALOG_INPUT_LOCK_LIST = 20;
	private static final int DIALOG_CLEAR_ALL = 30;

	private PreferenceScreen mChannelLockPreference;
	private PreferenceScreen mClearAllPreference;
	private Preference inputList;
	private CheckBoxPreference mLockToggleCheckBox;

	private Map<Integer, Long> mChannelsMap = new HashMap<Integer, Long>();

	// USDTVFramework instance
	//private final TvFramework mFrameInst = TvFramework.getInstance();

	// ParentalControlSettings instance

	//private final ParentalControl mParentalControl = mFrameInst
	//		.getParentalControlInstance();

	private boolean isTuner = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG," onCreate()");
		addPreferencesFromResource(R.xml.parental_lock_settings);

		mChannelLockPreference = (PreferenceScreen) findPreference(KEY_CHANNEL_LOCK);
		mClearAllPreference = (PreferenceScreen) findPreference(KEY_CLEAR_ALL);
		mLockToggleCheckBox = (CheckBoxPreference) findPreference(KEY_LOCK_TOGGLE);

		inputList = (Preference) findPreference(KEY_INPUT_LOCK_NEW);
		
		updateTunerStatus();
		
		//update the status of channel relative locks
		IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(TvIntents.INTENT_SOURCE_BIND_CHANGE);

        registerReceiver(mEventReceiver, intentFilter);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG," onResume()");
		
		//TvFramework.getInstance().getParentalControlInstance()
		//		.startPCLockedService(true);
		
		updateTunerStatus();
		
		// mLockToggleCheckBox.setChecked(getParentalLockStatus());
	}

	private void updateTunerStatus(){
		if (!Wrapper.getWrapperInstance().isTunerInput()) {
		    isTuner = false;
		}else{
		    isTuner = true;
		}
		Log.d(TAG," ---------updateTunerStatus()--isTuner:" + isTuner);
				
		try {
            mChannelLockPreference.setEnabled(isTuner );
            findPreference(KEY_PROGRAM_RATING).setEnabled(
            		isTuner );
        } catch (NullPointerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}
	
	public boolean getParentalLockStatus() {

		/*final USDTVPCData pcData = mParentalControl.getParentalSettings();
		Log.d(TAG, "**********getParentalLockStatus " + pcData);

		if (pcData != null) {
			Log.d(TAG, "**********getParentalLockStatus " + pcData.isPcEnable());
			return pcData.isPcEnable();
		}*/
		return false;
	}

	public void setParentalLockStatus(boolean lockable) {

		/*final USDTVPCData pcData = mParentalControl.getParentalSettings();
		Log.d(TAG, "**********setParentalLockStatus " + lockable);
		if (pcData != null) {
			Log.d(TAG, "*********888888888*setParentalLockStatus " + lockable);
			// pcData.setPcEnable(lockable);
			int value = 2;
			if (lockable == true) {
				value = 1;
			} else {
				value = 0;
			}
			Log.d(TAG, "*******999999999**setParentalLockStatus" + value);
			Wrapper.getWrapperInstance().setPCEnable(value);
		}*/
	}

	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		if (preference == inputList) {
			// Log.d("TAG", "--gadsgfdafdkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk ");
			Intent myintent = new Intent(ParentalLockSettings.this,
					MyCheck.class);
			startActivity(myintent);
		} else if (preference == mChannelLockPreference) {
			// showDialog(DIALOG_CHANNEL_LOCK_LIST);
			Intent intent = new Intent("com.hisense.settings.CHANNEL_LOCK_LIST");
			// intent.setAction("com.android.settings.CHANNEL_SKIP_LIST");
			startActivity(intent);
		} else if (preference == mClearAllPreference) {
			showDialog(DIALOG_CLEAR_ALL);
		} else if (preference == mLockToggleCheckBox) {
			boolean isChecked = ((CheckBoxPreference) preference).isChecked();
			Log.d(TAG, "**********preference == mLockToggleCheckBox "
					+ isChecked);
			setParentalLockStatus(isChecked);
		} else {
			return super.onPreferenceTreeClick(preferenceScreen, preference);
		}

		return false;
	}

	public boolean onPreferenceChange(Preference preference, Object objValue) {
		final String key = preference.getKey();
		updateTunerStatus();
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_CHANNEL_LOCK_LIST: {
			final ChannelLockedListener listener = new ChannelLockedListener(
					true);
			final CancelListener mCancelListener = new CancelListener();
			final AlertDialog.Builder builder = new AlertDialog.Builder(this)
					.setTitle(R.string.channel_lock)
					.setPositiveButton(android.R.string.ok, listener)
					.setOnCancelListener(mCancelListener)
					.setNegativeButton(android.R.string.cancel, mCancelListener);

			return builder.create();
		}
		case DIALOG_CLEAR_ALL: {
			AlertDialog.Builder b = new AlertDialog.Builder(this);
			b.setTitle(R.string.confirm_parental_lock_clear_dialog);
			b.setMessage(R.string.confirm_parental_lock_clear_dialog_message);
			b.setPositiveButton(R.string.confirm_parental_lock_clear_button,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {

							Intent myintent = new Intent(
									ParentalLockSettings.this,
									ResetModeActivity.class);
							startActivity(myintent);
							mLockToggleCheckBox.setChecked(false);
							
							dialog.dismiss();
							
						}
					});
			b.setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface d, int which) {

						}
					});
			return b.create();
		}
		}
		return null;
	}

	private class CancelListener implements DialogInterface.OnClickListener,
			DialogInterface.OnCancelListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			finish();
		}

		@Override
		public void onCancel(DialogInterface dialog) {
			finish();
		}
	}

	private class ChannelLockedListener implements
			DialogInterface.OnClickListener,
			DialogInterface.OnMultiChoiceClickListener {
		private int mCurrentIndex;
		private Set<Integer> mSelectedIndexSet;

		public ChannelLockedListener(boolean multipleSelect) {
			mCurrentIndex = 0;
			if (multipleSelect) {
				mSelectedIndexSet = new HashSet<Integer>();
			}
		}

		public void onClick(DialogInterface dialog, int which) {
			if (which == DialogInterface.BUTTON_POSITIVE) {
				if (mSelectedIndexSet != null) {
					final int size = mChannelsMap.size();
					// We'd like to sort the files by its index, so we do not
					// use Set iterator.
					for (int i = 0; i < size; i++) {
						if (mSelectedIndexSet.contains(i)) {
							Long id = mChannelsMap.get(i);
						}
					}
				}
			} else if (which == DialogInterface.BUTTON_NEGATIVE) {
				finish();
			} else {
				// Some file is selected.
				mCurrentIndex = which;
				if (mSelectedIndexSet != null) {
					if (mSelectedIndexSet.contains(which)) {
						mSelectedIndexSet.remove(which);
					} else {
						mSelectedIndexSet.add(which);
					}
				}
			}
		}

		public void onClick(DialogInterface dialog, int which, boolean isChecked) {
			if (mSelectedIndexSet == null
					|| (mSelectedIndexSet.contains(which) == isChecked)) {
			} else {
				onClick(dialog, which);
			}
		}

	}

	private void populateInputLists(ListPreference inputList) {
		buildSupportedInputListPreference(inputList);

		inputList
				.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
					public boolean onPreferenceChange(Preference preference,
							Object newValue) {
						return handleSelectInputLock(newValue);
					}
				});
	}

	private void buildSupportedInputListPreference(ListPreference inputList) {

		String[] supportedEntries = new String[5];// = new
													// String[supportedModes.length];
		String[] supportedValues = new String[5];// = new
													// String[supportedModes.length];
		for (int i = 0; i < 5/* supportedModes.length */; i++) {
			supportedEntries[i] = "entry: " + Integer.toString(i);
			supportedValues[i] = "entryvalue: " + Integer.toString(i);
		}
		inputList.setEntries(supportedEntries);
		inputList.setEntryValues(supportedValues);

	}

	private boolean handleSelectInputLock(Object newValue) {

		return false;
	}
	

	
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(mEventReceiver);
    }


    private BroadcastReceiver mEventReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(TvIntents.INTENT_SOURCE_BIND_CHANGE)){
                Log.d(TAG, "on Receive isTuner:"+Wrapper.getWrapperInstance().isTunerInput());
                updateTunerStatus();
            }
            
        }};
	
}
